// 统一的主题存储键名
const THEME_STORAGE_KEY = 'theme-mode';

export function getThemeMode() {
  // 优先使用统一的键名
  let savedMode = localStorage.getItem(THEME_STORAGE_KEY);

  // 如果没有找到，检查旧的键名并迁移
  if (!savedMode) {
    const oldTheme = localStorage.getItem('theme');
    if (oldTheme) {
      savedMode = oldTheme;
      // 迁移到新键名
      localStorage.setItem(THEME_STORAGE_KEY, savedMode);
      // 清理旧键名
      localStorage.removeItem('theme');
      console.log('主题设置已迁移到统一键名:', THEME_STORAGE_KEY);
    }
  }

  if (savedMode) {
    return savedMode;
  }

  // 检查系统偏好
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'dark';
  }

  return 'light';
}

export function setThemeMode(mode) {
  // 使用统一的键名保存
  localStorage.setItem(THEME_STORAGE_KEY, mode);

  // 清理可能存在的旧键名
  if (localStorage.getItem('theme')) {
    localStorage.removeItem('theme');
  }

  // 应用主题到DOM
  if (mode === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark');
  } else {
    document.documentElement.removeAttribute('data-theme');
  }
}

export function initTheme() {
  const mode = getThemeMode()
  setThemeMode(mode)
  return mode === 'dark'
} 